package com.zxp.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zxp.mall.cart.feign.ProductFeignService;
import com.zxp.mall.cart.interceptor.CartInterceptor;
import com.zxp.mall.cart.service.CartService;
import com.zxp.mall.cart.vo.Cart;
import com.zxp.mall.cart.vo.CartItem;
import com.zxp.mall.cart.vo.SkuInfoVo;
import com.zxp.mall.cart.vo.UserInfoTo;
import com.zxp.mall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";


    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
//        查询当前购物车是否有当前的skuId 商品
        String res = (String) ops.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
//            查询基本信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setPrice(skuInfoVo.getPrice());
                cartItem.setSkuId(skuId);
            }, executor);
            CompletableFuture<Void> getSkusaleAttrValues = CompletableFuture.runAsync(() -> {
//        远程查询sku的组合信息
                List<String> skusaleAttrValues = productFeignService.getSkusaleAttrValues(skuId);
                cartItem.setSkuAttr(skusaleAttrValues);
            }, executor);
            CompletableFuture.allOf(getSkuInfo, getSkusaleAttrValues).get();

            String jsonString = JSON.toJSONString(cartItem);
            ops.put(skuId.toString(), jsonString);
            return cartItem;
        } else {
//            购物车有商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            ops.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

// op    已经存在商品
//        不存在商品
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String jsonString = (String) ops.get(skuId.toString());
        return JSON.parseObject(jsonString, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        //        判断用户是否已经登录 threadlocal
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
//            已经登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
//            如果还有临时购物车的数据
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (!CollectionUtils.isEmpty(tempCartItems)) {
//                说明临时购物车有数据 需要合并操作
                for (CartItem cartItem : tempCartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
            }
            List<CartItem> items = getCartItems(cartKey);
            cart.setItems(items);
            clearCart(tempCartKey);
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> items = getCartItems(cartKey);
            cart.setItems(items);
        }
        return cart;
    }

    /**
     * 获取购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //        判断用户是否已经登录 threadlocal
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
//            已经登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

//        添加商品到购物车
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        return ops;
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        List<Object> values = ops.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItem> items = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return items;
        }
        return null;
    }

    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1);
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

    }

    @Override
    public void changeCountItem(Long skuId, Integer num) {
        if (num == 0) {
            deleteItem(skuId);
        } else {
            BoundHashOperations<String, Object, Object> cartOps = getCartOps();
            CartItem cartItem = getCartItem(skuId);
            cartItem.setCount(num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
        }
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();
        if (userInfo.getUserId() == null) {
            return null;
        }
        String cartKey = CART_PREFIX + userInfo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
//        筛选出选中的购物项
        List<CartItem> collect =
                cartItems.stream().filter(item -> item.getCheck()).map(item->{
//                    更新最新的商品价格
                    item.setPrice(productFeignService.getPrice(item.getSkuId()));
                    return item;
                }).collect(Collectors.toList());
        return collect;
    }
}
